package com.spring.netty;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

/**
 * 
 * @author Administrator
 *
 */
@Component
public class HttpServer {

	private final static Logger logger = LogManager.getLogger(HttpServer.class.getName());

	@PostConstruct
	public void start() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {

							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast(new ReadTimeoutHandler(60, TimeUnit.SECONDS));
							pipeline.addLast(new WriteTimeoutHandler(60, TimeUnit.SECONDS));
							pipeline.addLast("http-codec", new HttpServerCodec());
							pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
							ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
							pipeline.addLast("handler", new HttpServerHandler());

						}

					}).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // Boss线程内存池配置.
					.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);// Work线程内存池配置

			Channel ch = b.bind(900).sync().channel();
			logger.info("Web socket server started at port " + 900 + '.');
			logger.info("Open your browser and navigate to http://localhost:" + 900 + '/');

			ch.closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

}